package json

import (
	"encoding/json"
	"strings"
	"fmt"
	"os"
	"path/filepath"
	"log"
)

type User struct {
	Uid int `json:"userId" bson:"userId"`
	Name string `json:"userName" bson:"userName"`
}

func JsonDecode(s string) {
	var f interface{}
	err := json.Unmarshal([]byte(s), &f)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(f)
}

func JsonEncode(s interface{}) {
	var jsonString []byte
	jsonString, err := json.Marshal(s)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(string(jsonString))
}

func JsonDecodeByReader(s string) {
	decoder := json.NewDecoder(strings.NewReader(s))
	var u User
	err := decoder.Decode(&u)


	if err != nil {
		panic(err)
	}
	fmt.Println(u)

}


func JsonDecodeByFile (f string) {
	fp,_ := filepath.Abs(f)
	file,_ := os.Open(fp)
	decoder := json.NewDecoder(file)
	var user User
	err := decoder.Decode(&user)
	if err != nil {
		log.Println(err)
	}
	fmt.Println(user)
}